window.FsImgUploader = {
    resources: []
}
$(function () {
    let imageList = $('.content-img-list');
    // 鼠标经过显示删除按钮
    imageList.on('mouseover', '.content-img-list-item', function () {
        $(this).children('div').removeClass('hide');
    });
    // 鼠标离开隐藏删除按钮
    imageList.on('mouseleave', '.content-img-list-item', function () {
        $(this).children('div').addClass('hide');
    });
    // 单个图片删除
    imageList.on("click", '.content-img-list-item a .icon-minus', function () {
        let index = $(this).parent().parent().parent().index();
        FsImgUploader.resources.splice(index, 1);
        let boxId = ".content-img-list";
        addNewContent(boxId);
    });
});
//图片上传
$('#upload').on('change', function (e) {
    let imgSize = this.files[0].size;
    if (imgSize > 1024 * 500) { //1M
        return alert("上传图片不能超过500KB");
    }
    if (this.files[0].type !== 'image/png' && this.files[0].type !== 'image/jpeg' && this.files[0].type !== 'image/gif') {
        return alert("图片上传格式不正确");
    }

    let imgBox = '.content-img-list';
    let fileList = this.files;
    for (let i = 0; i < fileList.length; i++) {
        let imgSrcI = getObjectURL(fileList[i]);
        FsImgUploader.resources.push({
            imgFile: fileList[i],
            imgSrc: imgSrcI,
            imgName: fileList[i].name,
        });
    }
    addNewContent(imgBox);
    this.value = null; //上传相同图片
});

//删除
function removeImg(obj, index) {
    FsImgUploader.resources.splice(index, 1);
    let boxId = ".content-img-list";
    addNewContent(boxId);
}

//图片展示
function addNewContent(obj) {
    $(obj).html("");
    for (let index = 0; index < FsImgUploader.resources.length; index++) {
        let oldBox = $(obj).html();
        $(obj).html(
            `${oldBox}<li class="content-img-list-item">
                <img src="${FsImgUploader.resources[index].imgSrc}" alt="">
                <div class="hide">
                <a index="${index}" class="delete-btn">
                    <i class="icon icon-minus icon-3x"></i>
                </a>
                </div>
            </li>`
        );
    }
    if (FsImgUploader.resources.length < 1) {
        //显示上传按钮
        $('.content-img .file').show();
    } else {
        $('.content-img .file').hide();
    }

}

//建立可存取到file的url
function getObjectURL(file) {
    let url = null;
    if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL !== undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL !== undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}